<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>h5-localStorage</title>
</head>
<body>
<div style="float:left;position: relative;width: 800px;height: 400px;margin: auto 50%;left:-400px;border: #ff9999 1px solid">
    <h1>Web Storage(本地存储):只能存储字符串 </h1>
    <pre>
        特别说明:localStorage 和 sessionStorage 用法一样;失效时间不同
    </pre>
    <hr/>
    <label>k值:<input id="web_k" type="text" placeholder="仅支持字符串"></label>
    <label>v值:<input id="web_v" type="text" placeholder="仅支持字符串"></label>
    <button id="web_save">保存</button>
    <hr/>
    总数: <span id="web_count">0</span>
    <table border="1">
        <caption>数据展示</caption>
        <thead>
        <tr>
            <th>key</th>
            <th>value</th>
            <th>过期时间(固定1分钟)</th>
        </tr>
        </thead>
        <tbody id="web_list">
        <tr>
            <td>暂无数据</td>
            <td>暂无数据</td>
            <td>暂无数据</td>
        </tr>
        </tbody>
    </table>

</div>
<div style="float:left;position: relative;width: 800px;height: 400px;margin: auto 50%;left:-400px;top:100px; border: #fcd 1px solid">
    <h3 style="text-align: center">indexedDB位置: 浏览器->开发者模式->存储->indexed DB</h3>
    <ul id="index_ul">
        <li>请打开F12</li>
    </ul>
</div>

<script type="text/javascript">
    //  ------------------- Web Storage(本地存储) ----------------------------
    web_k = document.getElementById('web_k');
    web_v = document.getElementById('web_v');
    web_save = document.getElementById('web_save');
    web_count = document.getElementById('web_count');
    web_list = document.getElementById('web_list');
    localStorage.setItem('a', function () {
        alert('这是字符串')
    });
    showList(); //展示数据列表
    web_save.onclick = function () {
        if (web_k.value === '' || web_v.value === '') return false;
        localStorage.setItem(web_k.value, web_v.value); //往localStorage里设置k,v
        // localStorage.removeItem('leo');  //移除k
        showList();
    };

    // 展示当前的localStorage数据
    function showList() {
        let html = '', count = 0;
        for (let i = 0; i < localStorage.length; i++) {
            let key = localStorage.key(i), value = localStorage.getItem(key);
            html += '<tr><td>' + key + '</td><td>' + value + '</td><td></td></tr>';
            count++;
        }
        web_list.innerHTML = html;
        web_count.innerText = count + '';
    }

    // 每间隔1分钟 清除所有k,v
    setInterval(function () {
        localStorage.clear();
        showList();
    }, 60000);
</script>
<script type="text/javascript">
    let index_ul = document.getElementById('index_ul');
    // ------------------------indexedDB---------------------------
    let request = indexedDB.open('db_du', 4);
    request.onerror = function (event) {
        console.log('数据库打开报错');
    };
    request.onsuccess = function (event) {
        let db = request.result;
        console.log('数据库打开成功');
        // add(db,tableData);
        // add(db,tableData2);
        // add(db,tableData3);
        // add(db,tableData4);
        // add(db,tableData5);
        // add(db,tableData6);
        // update(db,'leon3');
        // read(db,'leon2');
        // readAll(db,'leon2')
        readByIndex(db)

    };
    request.onupgradeneeded = function (event) {
        let db = event.target.result;
        console.log('数据库版本号升级了');

        // if (db.objectStoreNames.contains('person')) db.deleteObjectStore('person');//删除表
        // delDb(db,'db_du'); //删除 db

        let objectStore;  //如果person表不存在,则创建  ==>设置自增主键: {autoIncrement: true}    自定义主键: {keyPath: 字段名}
        objectStore = db.createObjectStore('person', { keyPath: 'id' });
        objectStore.createIndex('nameIndex', 'name', { unique: false }); //给name字段创建唯一索引nameIndex

    }

    let tableData ={ id: 'celia1', name: 'ce', age: 18, email: 'celia1@qq.com' },
        tableData2 ={ id: 'celia2', name: 'li', age: 28, email: 'celia2@qq.com' },
        tableData3 ={ id: 'celia3', name: 'le', age: 38, email: 'celia3@qq.com' },
        tableData4 ={ id: 'leon1', name: 'wang', age: 23, email: 'celia4@qq.com' },
        tableData5 ={ id: 'leon2', name: 'wangBa', age: 25, email: 'celia5@qq.com' },
        tableData6 ={ id: 'leon3', name: 'ruanDan', age: 48, email: 'celia6@qq.com' };
    // 添加数据
    function add(db,data) {
        let request = db.transaction(['person'], 'readwrite')  //新建事务;  readwrite(读写)/readonly(只读)
            .objectStore('person')  //获取表对象
            .add(data); //向表格写入数据;通过监听对象的success事件和error事件,了解是否写入成功。
        request.onsuccess = function (event) { console.log('数据写入成功'); };
        request.onerror = function (event) { console.log('数据写入失败'); };
    }
    function read(db,key) {
        let table = db.transaction(['person']).objectStore('person');
        // 1-getKey(key) 判断key是否存在     2-get(key) 获取key对应的数据      3-getAll() 获取所有数据       4-getAllKeys() 获取所有key
        // 4-clear() 清除所有数据            4-put() 修改数据                 6-delete() 删除数据          7-add(value) 增加数据
        let request = table.get(key);
        // 通过监听对象的success事件和error事件,了解是否读取成功
        request.onerror = function(event) {console.log('事务失败');};
        request.onsuccess = function( event) {
            if (request.result) {
                console.log('id: '+request.result.id+' Name: ' + request.result.name+' Age: '+request.result.age +' Email:'+request.result.email);
            } else {
                console.log('未获得数据记录');
            }
        };
    }
    function update(db,key) {
        let request = db.transaction(['person'], 'readwrite')
            .objectStore('person')
            .put({ id: key, name: '李四', age: 35, email: 'lisi@example.com' });
        request.onsuccess = function (event) {console.log('数据更新成功');};
        request.onerror = function (event) {console.log('数据更新失败');}
    }

    function readAll(db,select) {
        let table = db.transaction('person').objectStore('person');
        /*
            IDBRange: 指定游标范围
                IDBRange.upperBound(x) // All keys ≤ x
                IDBRange.upperBound(x, true) //All keys < x
                IDBRange.lowerBound(y)   //All keys ≥ y
                IDBRange.lowerBound(y, true) //All keys > y
                IDBRange.only(z) //The key = z
                IDBRange.bound(x, y) // All keys ≥ x && ≤ y
                IDBRange.bound(x, y, true, true) //All keys > x && < y
                IDBRange.bound(x, y, true, false) //All keys > x && ≤ y
                IDBRange.bound(x, y, false, true) //All keys ≥ x && < y
            direction(游标的方向): next(顺序查询)/nextUnique(顺序唯一查询)/prev(逆序查询)/prevUnique(逆序唯一查询)
         */
        // 监听游标的onsuccess事件
        let cursor = table.openCursor(IDBKeyRange.only(select),'prev');//参数1: 主键获取range   参数2:游标的方向,
        cursor.onsuccess = function (event) {
            let cursor = event.target.result;
            if (cursor) {
                console.log('Id: ' + cursor.key +' Name: ' + cursor.value.name+ ' Age: ' + cursor.value.age+' Email: ' + cursor.value.email);
                cursor.continue();
            } else {
                console.log('没有更多数据了！');
            }
        };
    }

    //
    function readByIndex(db){
        let transaction = db.transaction(['person'], 'readonly');
        let table = transaction.objectStore('person');
        let index = table.index('nameIndex');
        /*
            IDBIndex对象:
                (1) index.get('李四') //通过索引值获取对象
                (2) index.getAll(); //获取所有记录
                    all.onsuccess = function (e) { console.log( e.target.result); }

         */
        
        // let request = index.get('李四');
        // request.onsuccess = function (e) { // 监听数据获取成功事件
        //     let result = e.target.result;
        //     if (result) console.log('Id: ' + result.id +' Name: ' + result.name+ ' Age: ' + result.age+' Email: ' + result.email);
        //     else console.log('not data');
        // }
        let all = index.getAll(); //获取所有记录
        all.onsuccess = function (e) {
            console.log( e.target.result);
            let html = '<li style="color: #ff9999">当前IndexedDB-->db_du数据库-->person的数据:</li>';
            for (const elem of e.target.result) {
                html +='<li> id = '+ elem.id +' name = '+ elem.name +' age = '+elem.age+'</li>';
            }
            index_ul.innerHTML = html;
        }

    }

    function delDb(db,dbName){
        db.close(); // 关闭数据库
        // 删除数据库文件
        let deleteRequest = indexedDB.deleteDatabase(dbName);
        deleteRequest.onerror = function(event) {console.error('Delete database error: ' + event.target.errorCode);};
        deleteRequest.onsuccess = function() {console.log('Database deleted successfully');};
    }

</script>
</body>
</html>